/*   Copyright (C) 2008  Jeroen v. Schagen & Youri Lima
 *
 *   This program is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

using System;
using System.Text;
using System.Drawing;

using Engine.Core;
using Engine.Math;
using Engine.Rendering.Library;

namespace Engine.Rendering
{
    public class Model : Component, IRenderable
    {
        private String file;

        private Microsoft.DirectX.Direct3D.Mesh mesh;
        private Microsoft.DirectX.Direct3D.Material[] materials;
        private Microsoft.DirectX.Direct3D.Texture[] textures;

        public Model(String name, String mesh) : base(name)
        {
            file = mesh;
        }

        public void Init(Microsoft.DirectX.Direct3D.Device device)
        {
            if (file.Equals(""))
            {
                throw new Exception("No source for the meshfile specified");
            }

            else
            {
                // Retrieve information from manager
                MeshInformation nm = MeshManager.Instance.GetMesh(file);

                // Setup mesh information
                mesh = nm.Mesh;
                materials = nm.Materials;
                textures = nm.Textures;
            }
        }

        public void Render(Microsoft.DirectX.Direct3D.Device device, Camera camera)
        {
            if (camera.Visible(this))
            {
                // Setup device
                device.VertexFormat = Microsoft.DirectX.Direct3D.CustomVertex.PositionColored.Format;
                device.Transform.World = DirectX.ToDirectX((Matrix4) this.GetAdapter(typeof(Matrix4)));

                // Draw material
                for (int i = 0; i < materials.Length; i++)
                {
                    device.Material = materials[i];
                    device.SetTexture(0, textures[i]);
                    mesh.DrawSubset(i);
                }
            }
        }

        public String Meshfile
        {
            get { return file; }
            set { file = value; }
        }
    }
}